import Vue from 'vue'
import VueRouter from 'vue-router'

// 路由懒加载的形式
const Login = () => import('@/views/Login/Login.vue')
const Main = () => import('@/views/Main/Main.vue')
const Home = () => import('@/views/Home/Home.vue')
const User = () => import('@/views/User/User.vue')
const Chat = () => import('@/views/Chat/Chat.vue')
const Cart = () => import('@/views/Cart/Cart.vue')
const ArticleDetail = () => import('@/views/ArticleDetail/ArticleDetail.vue')
const UserEdit = () => import('@/views/UserEdit/UserEdit.vue')
// const originalPush = VueRouter.prototype.push
// VueRouter.prototype.push = function push(location, onResolve, onReject) {
//   if (onResolve || onReject) {
//     return originalPush.call(this, location, onResolve, onReject)
//   }
//   return originalPush.call(this, location).catch((err) => err)
// }

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    component: Login,
    name: 'login'
  },
  {
    path: '/',
    component: Main,
    children: [
      {
        path: '',
        component: Home,
        name: 'home'
      },
      {
        path: 'user',
        component: User,
        name: 'user'
      },
      {
        path: 'cart',
        component: Cart,
        name: 'cart'
      }
    ]
  },
  {
    path: '/chat',
    component: Chat,
    name: 'chat'
  },
  {
    path: '/details/:id',
    component: ArticleDetail,
    name: 'articleDetail'
  },
  {
    path: '/useredit',
    component: UserEdit,
    name: 'useredit'
  }
]

const router = new VueRouter({
  routes
})

// pathArr需要登录的页面
const pathArr = ['/user', '/cart']
// 全局前置路由守卫,路由拦截
router.beforeEach((to, from, next) => {
  // 判断要跳转的页面 是否需要登录
  if (pathArr.indexOf(to.path) !== -1) {
    // 获取本地的vuex的数据
    const allStateObj = JSON.parse(localStorage.getItem('newsState'))
    if (allStateObj && allStateObj.tokenInfo.token) {
      next()
    } else {
      next('/login?pre=' + to.fullPath)
    }
  } else {
    next()
  }
})

export default router
